Search


📜 [專欄新文章] Solidity Weekly #8
✍️ mingde...

  • Share this:


📜 [專欄新文章] Solidity Weekly #8
✍️ mingderwang
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium

Events 和 Logs 的用法

從 #8 開始, 我想增加短連結方式(links 分享), 介紹大家更多有關 Solidity 的好文章. 若有想共筆的人, 也可以將連結與短文介紹, 寄到 twitter @mingderwang 給我, 我會放在下一期的 Solidity Weekly 刊登.

TL;DR

事實上 solidity 本身只有 event 指令, 沒有 log 指令(註: log0, log1 …它們屬於 assembly 用的 low-level function). Events 是用來實現 logs 的方法, 把它想成是比記載在 storage 裡更便宜的資料儲存方法. 但 logs 只能從區塊鏈的外部, 比如說用 web3.js 來讀取, 正確的說法應該是 trigger 的方式, 透由 web3.js 的 watch 指令來看到 ”事件” 的發生, 所以也可以用來更新 Dapp 的畫面.

這裡提到比記載在 storage 裡更便宜, 指的是相同的資料量, 放在記憶體裡當然貴了. 在區塊鏈的世界裡, 用到 miner 電腦的資源越多, 所要花費的 gas 就越高. LOG 運算碼(opcode)本身需花 375 gas, 再加上每個 byte 只要花 8 gas, 相較於 contract storage 每 32 bytes 就要 20,000 gas 實在差很大.

最後, 要提到的是 event 定義裡的參數(如下範例的 _market 和 _sender), 可以加 indexed 保留字讓該參數可以當參數被查詢, 又稱為 topics. 但最多只能用 3 個 (其實原本有四個 topics, 但第一個已經被 event 的識別值給用掉了). 如此一來 web3.js 就可以針對某個 _market 或 _sender 的值來查詢. 沒有用 indexed 的只能當 data 讀取. (若要 indexed 更詳細用法, 可參考 這裡)

contract CryptoExchange {

event Deposit(uint256 indexed _market, address indexed _sender, uint256 _amount, uint256 _time);

function deposit(uint256 _amount, uint256 _market) returns (int256) { // perform deposit, update user’s balance, etc Deposit(_market, msg.sender, _amount, now);}

links 分享;

Solidity撰寫智能合約與注意事項(二) — (NIC Lin)

Technical Introduction to Events and Logs in Ethereum — (ConsenSys)

[無用] 如何在 token 發行量裡埋彩蛋? — (Roger Wu)

後記;

Events 在文法上, 要在 event 的呼叫前面增加 emit 字眼, 否則 solidity compiler 會有 “Invoking events without “emit” prefix is deprecated.” 的警告出現.

*emit 適用於 solidity ^0.4.21;

Solidity Weekly #8 was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.

👏 歡迎轉載分享鼓掌


Tags:

About author
not provided
We have regular meeting twice per month on discussing blockchain technology, smart contracts and DApps development! We would love to have you join us!
View all posts